Popular Searches
Popular Course Categories
Popular Courses

Uploading and managing images and files

Uploading and managing images and files

Firebase with Flutter

Uploading and Managing Images and Files in Flutter with Firebase Storage

Uploading and managing images and files is a common requirement in modern Flutter applications. Applications such as social media platforms, e-commerce apps, learning platforms, chat applications, profile management systems, and document management systems need a reliable way to store user-generated files.

Firebase Cloud Storage provides scalable cloud object storage for images, videos, documents, audio files, PDFs, and other user-generated content. In Flutter, the firebase_storage package provides APIs for uploading, downloading, monitoring, updating metadata, listing, and deleting files.

For Flutter learning resources, visit JustAcademy Flutter Training Course and Register for Flutter Course Demo.


1. What Does Uploading and Managing Files Mean?

Uploading means transferring a file from the user's device to a cloud storage service. Managing files includes retrieving, displaying, downloading, updating metadata, organizing, replacing, and deleting stored files.

A typical application flow looks like this:

User selects image/file
        ↓
Flutter receives local file
        ↓
Validate file
        ↓
Create Firebase Storage reference
        ↓
Upload file
        ↓
Monitor upload progress
        ↓
Get download URL
        ↓
Store file information
        ↓
Display or download file
        ↓
Update or delete when required

2. Examples of Files Used in Flutter Applications

  • Profile pictures
  • Product images
  • Cover images
  • Gallery images
  • PDF documents
  • Resumes
  • Certificates
  • Videos
  • Audio files
  • Chat attachments
  • Invoices
  • Application documents

3. Firebase Storage Architecture

Firebase Storage stores the actual files in a Cloud Storage bucket. Firestore can be used separately to store application information related to those files, such as file name, URL, user ID, category, and upload date.

Flutter Application
       |
       +---- Firebase Authentication
       |          |
       |          +---- User ID
       |
       +---- Firebase Storage
       |          |
       |          +---- Images
       |          +---- Videos
       |          +---- Documents
       |          +---- Audio
       |
       +---- Cloud Firestore
                  |
                  +---- File URL
                  +---- File name
                  +---- User ID
                  +---- Upload date

4. Prerequisites

Before implementing file uploads, make sure the Flutter project is connected to Firebase.

  • Flutter SDK
  • Flutter project
  • Firebase project
  • Firebase Core configuration
  • FlutterFire CLI configuration
  • Cloud Storage bucket
  • Firebase Storage package
  • Image/file picker package when selecting files from the device

5. Configure Firebase Storage

Firebase Storage needs to be configured in the Firebase project before files can be uploaded.

Run the following command to configure Firebase for the Flutter application:

flutterfire configure

Then add Firebase Storage:

flutter pub add firebase_storage

Import the package:

import 'package:firebase_storage/firebase_storage.dart';

Firebase's Flutter integration uses the firebase_storage package for Cloud Storage operations.

6. Initialize Firebase

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  runApp(const MyApp());
}

7. Access Firebase Storage

The main Firebase Storage instance can be accessed using FirebaseStorage.instance.

final storage = FirebaseStorage.instance;

You can create a reference to the root of the Storage bucket:

final storageRef = FirebaseStorage.instance.ref();

8. What Is a Storage Reference?

A Storage Reference is a pointer to a location or file inside the Firebase Storage bucket. References are used for uploading, downloading, retrieving metadata, updating metadata, and deleting files.

final storageRef = FirebaseStorage.instance.ref();

final imagesRef = storageRef.child('images');

final profileRef = storageRef.child('images/profile.jpg');

9. Understanding Storage Paths

Files can be organized using paths similar to folders.

images/profile.jpg
images/products/laptop.jpg
documents/resume.pdf
videos/course.mp4
audio/lesson.mp3

Although Cloud Storage uses object paths rather than traditional folders, these paths provide a hierarchical structure for organizing files.

10. Recommended File Organization

users/
  userId/
    profile.jpg
    documents/
      resume.pdf
      certificate.pdf

products/
  productId/
    main.jpg
    gallery/
      image1.jpg
      image2.jpg

posts/
  postId/
    cover.jpg
    attachments/

videos/
  videoId/
    video.mp4

11. Selecting Images in Flutter

A common workflow is to use an image picker to allow the user to select an image from the gallery or camera.

For example, the image_picker package can be used:

flutter pub add image_picker

Import it:

import 'dart:io';
import 'package:image_picker/image_picker.dart';

12. Pick an Image from Gallery

Future pickImage() async {
  final picker = ImagePicker();

  final pickedFile = await picker.pickImage(
    source: ImageSource.gallery,
  );

  if (pickedFile == null) {
    return null;
  }

  return File(pickedFile.path);
}

13. Pick an Image from Camera

Future takePhoto() async {
  final picker = ImagePicker();

  final pickedFile = await picker.pickImage(
    source: ImageSource.camera,
  );

  if (pickedFile == null) {
    return null;
  }

  return File(pickedFile.path);
}

14. Upload an Image to Firebase Storage

After selecting an image, create a Storage reference and upload the file using putFile(). Firebase Storage also supports putData() and putString() for other types of upload data.

Future uploadImage(File imageFile) async {
  final ref = FirebaseStorage.instance
      .ref()
      .child('images/profile.jpg');

  await ref.putFile(imageFile);

  print('Image uploaded successfully');
}

15. Upload Image with a Dynamic File Name

Using the same file name for multiple uploads can cause files to be overwritten. A unique file name is often better when each upload should be preserved.

Future uploadImage(
  File imageFile,
  String userId,
) async {
  final fileName =
      DateTime.now().millisecondsSinceEpoch.toString();

  final ref = FirebaseStorage.instance
      .ref()
      .child('users/$userId/images/$fileName.jpg');

  await ref.putFile(imageFile);

  return await ref.getDownloadURL();
}

16. Upload with File Metadata

Metadata can describe the file, including its MIME type. For example, an image can be uploaded with image/jpeg as its content type.

final metadata = SettableMetadata(
  contentType: 'image/jpeg',
);

final ref = FirebaseStorage.instance
    .ref()
    .child('images/photo.jpg');

await ref.putFile(
  imageFile,
  metadata,
);

17. Common Content Types

File Type Content Type
JPEGimage/jpeg
PNGimage/png
GIFimage/gif
PDFapplication/pdf
MP4video/mp4
MP3audio/mpeg
Texttext/plain

18. Complete Image Upload Function

Future uploadProfileImage(
  File imageFile,
  String userId,
) async {
  final ref = FirebaseStorage.instance
      .ref()
      .child('users/$userId/profile.jpg');

  final metadata = SettableMetadata(
    contentType: 'image/jpeg',
  );

  await ref.putFile(
    imageFile,
    metadata,
  );

  final url = await ref.getDownloadURL();

  return url;
}

19. Getting the Download URL

After uploading a file, getDownloadURL() can be used to obtain a URL that the application can use to access the file.

final ref = FirebaseStorage.instance
    .ref()
    .child('images/profile.jpg');

final url = await ref.getDownloadURL();

print(url);

20. Display Firebase Storage Image

Once the download URL is available, the image can be displayed using Image.network().

Image.network(
  imageUrl,
  width: 150,
  height: 150,
  fit: BoxFit.cover,
)

21. Display Image with Placeholder

Image.network(
  imageUrl,
  width: 150,
  height: 150,
  fit: BoxFit.cover,
  loadingBuilder: (
    context,
    child,
    loadingProgress,
  ) {
    if (loadingProgress == null) {
      return child;
    }

    return const Center(
      child: CircularProgressIndicator(),
    );
  },
)

22. Upload Progress

Firebase Storage provides upload task events that can be used to show upload progress in the Flutter UI. The task can report running, paused, success, canceled, and error states.

final ref = FirebaseStorage.instance
    .ref()
    .child('images/photo.jpg');

final uploadTask = ref.putFile(imageFile);

uploadTask.snapshotEvents.listen((snapshot) {
  final progress =
      snapshot.bytesTransferred / snapshot.totalBytes;

  print(
    'Upload: ${(progress * 100).toStringAsFixed(0)}%',
  );
});

23. Upload Progress Indicator

double progress = 0;

uploadTask.snapshotEvents.listen((snapshot) {
  setState(() {
    progress =
        snapshot.bytesTransferred / snapshot.totalBytes;
  });
});

Display the progress:

LinearProgressIndicator(
  value: progress,
)

24. Upload Task States

State Meaning
TaskState.runningFile is currently uploading.
TaskState.pausedUpload has been paused.
TaskState.successUpload completed successfully.
TaskState.canceledUpload was canceled.
TaskState.errorUpload failed.

25. Pause an Upload

final uploadTask = ref.putFile(largeFile);

final paused = await uploadTask.pause();

print('Paused: $paused');

26. Resume an Upload

final resumed = await uploadTask.resume();

print('Resumed: $resumed');

27. Cancel an Upload

final canceled = await uploadTask.cancel();

print('Canceled: $canceled');

Firebase Storage supports pausing, resuming, and canceling upload tasks, which is useful when dealing with large files or unreliable network conditions.

28. Upload PDF Files

Firebase Storage is not limited to images. PDF files and other documents can also be uploaded.

Future uploadPdf(
  File pdfFile,
  String userId,
) async {
  final ref = FirebaseStorage.instance
      .ref()
      .child('users/$userId/documents/resume.pdf');

  await ref.putFile(
    pdfFile,
    SettableMetadata(
      contentType: 'application/pdf',
    ),
  );

  return await ref.getDownloadURL();
}

29. Upload Video Files

Future uploadVideo(
  File videoFile,
  String videoId,
) async {
  final ref = FirebaseStorage.instance
      .ref()
      .child('videos/$videoId/video.mp4');

  await ref.putFile(
    videoFile,
    SettableMetadata(
      contentType: 'video/mp4',
    ),
  );

  return await ref.getDownloadURL();
}

30. Upload Audio Files

Future uploadAudio(
  File audioFile,
  String audioId,
) async {
  final ref = FirebaseStorage.instance
      .ref()
      .child('audio/$audioId/audio.mp3');

  await ref.putFile(
    audioFile,
    SettableMetadata(
      contentType: 'audio/mpeg',
    ),
  );

  return await ref.getDownloadURL();
}

31. Downloading Files

Firebase Storage supports downloading file data into memory or downloading directly to a local file. The getData() method loads data into memory, while writeToFile() can save a file locally.

Download Data into Memory

final ref = FirebaseStorage.instance
    .ref()
    .child('images/photo.jpg');

final data = await ref.getData();

if (data != null) {
  print('Downloaded ${data.length} bytes');
}

Download to Local File

final ref = FirebaseStorage.instance
    .ref()
    .child('documents/resume.pdf');

final file = File('/local/path/resume.pdf');

final downloadTask = ref.writeToFile(file);

downloadTask.snapshotEvents.listen((snapshot) {
  print(snapshot.state);
});

32. Important Difference: getData() vs writeToFile()

Method Use
getData()Loads file bytes into memory.
writeToFile()Downloads the file directly to a local file.
getDownloadURL()Returns a URL for accessing the file.

For large files, loading the entire file into memory can cause memory problems, so a local-file download approach can be more appropriate.

33. Getting File Metadata

File metadata provides information such as file name, size, content type, creation time, and update time.

final ref = FirebaseStorage.instance
    .ref()
    .child('images/photo.jpg');

final metadata = await ref.getMetadata();

print('Name: ${metadata.name}');
print('Size: ${metadata.size}');
print('Type: ${metadata.contentType}');
print('Created: ${metadata.timeCreated}');

34. Important Metadata Properties

Property Description
nameFile name.
sizeFile size.
contentTypeMIME type.
fullPathFull Storage path.
timeCreatedFile creation time.
updatedLast update time.
customMetadataCustom key-value metadata.

35. Updating File Metadata

Metadata can be updated after a file has been uploaded using updateMetadata().

final ref = FirebaseStorage.instance
    .ref()
    .child('images/photo.jpg');

final metadata = SettableMetadata(
  contentType: 'image/jpeg',
  customMetadata: {
    'category': 'profile',
    'owner': 'user123',
  },
);

await ref.updateMetadata(metadata);

36. Deleting Files

To delete a file, create a reference to the file and call delete().

final ref = FirebaseStorage.instance
    .ref()
    .child('images/photo.jpg');

await ref.delete();

37. Delete File Function

Future deleteFile(String path) async {
  final ref = FirebaseStorage.instance.ref().child(path);

  await ref.delete();

  print('File deleted');
}

38. Replacing an Image

When an application uses a fixed Storage path, uploading another file to that same path can replace the existing object.

final ref = FirebaseStorage.instance
    .ref()
    .child('users/$userId/profile.jpg');

await ref.putFile(
  newImage,
  SettableMetadata(
    contentType: 'image/jpeg',
  ),
);

39. Delete Old File and Upload New File

If unique file names are used, the application may need to delete the old file explicitly when replacing it.

Future replaceImage(
  File newImage,
  String oldPath,
  String userId,
) async {
  try {
    final oldRef =
        FirebaseStorage.instance.ref().child(oldPath);

    await oldRef.delete();
  } catch (e) {
    print('Old file could not be deleted: $e');
  }

  final newRef = FirebaseStorage.instance
      .ref()
      .child('users/$userId/images/new_image.jpg');

  await newRef.putFile(newImage);

  return await newRef.getDownloadURL();
}

40. Listing Files

Firebase Storage supports listing the contents of a Storage location. The SDK returns files as items and directories as prefixes.

final storageRef = FirebaseStorage.instance
    .ref()
    .child('images');

final result = await storageRef.listAll();

for (final item in result.items) {
  print(item.fullPath);
}

for (final prefix in result.prefixes) {
  print('Folder: ${prefix.fullPath}');
}

41. listAll() vs list()

listAll() retrieves all results and is convenient for small directories. For larger directories, paginated listing with list() can be more appropriate.

Method Purpose
listAll()Retrieves all items and prefixes.
list()Supports paginated listing for larger directories.

42. Display a List of Uploaded Images

Future> getImageUrls() async {
  final ref = FirebaseStorage.instance
      .ref()
      .child('images');

  final result = await ref.listAll();

  final List urls = [];

  for (final item in result.items) {
    final url = await item.getDownloadURL();
    urls.add(url);
  }

  return urls;
}

43. Display Images with GridView

FutureBuilder>(
  future: getImageUrls(),
  builder: (context, snapshot) {
    if (snapshot.connectionState ==
        ConnectionState.waiting) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    if (snapshot.hasError) {
      return const Center(
        child: Text('Unable to load images'),
      );
    }

    final images = snapshot.data ?? [];

    if (images.isEmpty) {
      return const Center(
        child: Text('No images found'),
      );
    }

    return GridView.builder(
      gridDelegate:
          const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
      ),
      itemCount: images.length,
      itemBuilder: (context, index) {
        return Image.network(
          images[index],
          fit: BoxFit.cover,
        );
      },
    );
  },
)

44. Managing File Information with Firestore

A common application architecture stores the actual file in Firebase Storage and stores related application data in Firestore.

products/product123
{
  "name": "Laptop",
  "price": 65000,
  "imageUrl": "https://...",
  "storagePath": "products/product123/image.jpg",
  "createdAt": "timestamp"
}

The actual image is stored in Firebase Storage:

products/product123/image.jpg

45. Save File URL in Firestore

final imageUrl = await ref.getDownloadURL();

await FirebaseFirestore.instance
    .collection('products')
    .doc(productId)
    .set({
  'name': 'Laptop',
  'imageUrl': imageUrl,
  'storagePath': ref.fullPath,
  'createdAt': FieldValue.serverTimestamp(),
});

46. Why Store the Storage Path?

Saving the Storage path along with the download URL makes it easier to identify the corresponding Storage object when the application needs to replace or delete it.

{
  "imageUrl": "https://...",
  "storagePath": "products/product123/image.jpg"
}

47. Authentication and File Management

Private file management should generally be connected to Firebase Authentication. The user's UID can be included in the Storage path.

final user = FirebaseAuth.instance.currentUser;

if (user == null) {
  return;
}

final userId = user.uid;

final ref = FirebaseStorage.instance
    .ref()
    .child('users/$userId/profile.jpg');

48. User-Specific File Structure

users/
  user123/
    profile.jpg
    documents/
      resume.pdf

users/
  user456/
    profile.jpg
    documents/
      certificate.pdf

49. Storage Security Rules

Firebase Storage Security Rules determine who can read and write files. Production applications should use restrictive rules that match the application's authentication and authorization requirements.

A basic authenticated-user rule can look like this:

rules_version = '2';

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != null;
    }
  }
}

50. User-Specific Security Rules

If users should only access their own files, the user's UID can be matched against the authenticated user's UID.

rules_version = '2';

service firebase.storage {
  match /b/{bucket}/o {
    match /users/{userId}/{allPaths=**} {
      allow read, write: if request.auth != null
                          && request.auth.uid == userId;
    }
  }
}

51. File Validation

Before uploading a file, applications should validate it according to the application's requirements.

  • Check whether a file was selected.
  • Check the file extension.
  • Check the MIME type where available.
  • Check the file size.
  • Restrict unwanted file types.
  • Use appropriate Storage Security Rules.
  • Show an error if validation fails.

52. Image Extension Validation

bool isValidImage(String path) {
  final lowerPath = path.toLowerCase();

  return lowerPath.endsWith('.jpg') ||
      lowerPath.endsWith('.jpeg') ||
      lowerPath.endsWith('.png');
}

53. File Size Validation

Future isFileSizeValid(
  File file,
  double maxSizeMB,
) async {
  final sizeInBytes = await file.length();
  final sizeInMB =
      sizeInBytes / (1024 * 1024);

  return sizeInMB <= maxSizeMB;
}

54. Upload with Validation

Future uploadValidatedImage(
  File imageFile,
  String userId,
) async {
  final validSize =
      await isFileSizeValid(imageFile, 5);

  if (!validSize) {
    print('Image must be smaller than 5 MB');
    return null;
  }

  if (!isValidImage(imageFile.path)) {
    print('Invalid image format');
    return null;
  }

  final ref = FirebaseStorage.instance
      .ref()
      .child('users/$userId/profile.jpg');

  await ref.putFile(
    imageFile,
    SettableMetadata(
      contentType: 'image/jpeg',
    ),
  );

  return await ref.getDownloadURL();
}

55. Error Handling

Upload, download, and delete operations can fail because of missing files, permissions, network problems, or other conditions. These operations should therefore be wrapped in appropriate error handling.

try {
  await ref.putFile(file);

  print('Upload successful');
} on FirebaseException catch (e) {
  print('Firebase error: ${e.code}');
  print('Message: ${e.message}');
} catch (e) {
  print('Unexpected error: $e');
}

56. Common Storage Errors

Error Possible Meaning
object-not-foundThe requested file does not exist.
unauthorizedThe user does not have permission.
canceledThe operation was canceled.
retry-limit-exceededThe operation exceeded the retry limit.
invalid-checksumUploaded data failed integrity validation.

57. Upload Loading State

The UI should provide feedback while a file is uploading.

bool isUploading = false;

Future uploadFile(File file) async {
  setState(() {
    isUploading = true;
  });

  try {
    final ref = FirebaseStorage.instance
        .ref()
        .child('files/document.pdf');

    await ref.putFile(file);
  } finally {
    setState(() {
      isUploading = false;
    });
  }
}

58. Upload Button

ElevatedButton(
  onPressed: isUploading
      ? null
      : () {
          uploadSelectedFile();
        },
  child: isUploading
      ? const CircularProgressIndicator()
      : const Text('Upload File'),
)

59. Complete Image Upload Flow

Future selectAndUploadImage(
  String userId,
) async {
  final picker = ImagePicker();

  final pickedFile = await picker.pickImage(
    source: ImageSource.gallery,
  );

  if (pickedFile == null) {
    return;
  }

  final imageFile = File(pickedFile.path);

  final fileName =
      DateTime.now().millisecondsSinceEpoch.toString();

  final ref = FirebaseStorage.instance
      .ref()
      .child('users/$userId/images/$fileName.jpg');

  final uploadTask = ref.putFile(
    imageFile,
    SettableMetadata(
      contentType: 'image/jpeg',
    ),
  );

  uploadTask.snapshotEvents.listen((snapshot) {
    final progress =
        snapshot.bytesTransferred /
        snapshot.totalBytes;

    print(
      'Progress: ${(progress * 100).toStringAsFixed(0)}%',
    );
  });

  await uploadTask;

  final url = await ref.getDownloadURL();

  print('Image URL: $url');
}

60. Creating a Reusable Storage Service

For larger Flutter applications, Firebase Storage operations should be separated from UI widgets.

class StorageService {
  final FirebaseStorage _storage =
      FirebaseStorage.instance;

  Future uploadFile(
    File file,
    String path,
    String contentType,
  ) async {
    final ref = _storage.ref().child(path);

    await ref.putFile(
      file,
      SettableMetadata(
        contentType: contentType,
      ),
    );

    return await ref.getDownloadURL();
  }

  Future deleteFile(String path) async {
    final ref = _storage.ref().child(path);
    await ref.delete();
  }

  Future getMetadata(
    String path,
  ) async {
    final ref = _storage.ref().child(path);
    return await ref.getMetadata();
  }
}

61. Using the Storage Service

final storageService = StorageService();

final imageUrl = await storageService.uploadFile(
  imageFile,
  'users/$userId/profile.jpg',
  'image/jpeg',
);

print(imageUrl);

62. Recommended Project Structure

lib/
├── main.dart
├── firebase_options.dart
├── models/
│   └── file_model.dart
├── services/
│   └── storage_service.dart
├── repositories/
│   └── file_repository.dart
├── screens/
│   ├── upload_screen.dart
│   ├── gallery_screen.dart
│   └── profile_screen.dart
└── widgets/
    ├── upload_button.dart
    ├── upload_progress.dart
    └── file_card.dart

63. File Management State Flow

Initial
   ↓
Select File
   ↓
Validate File
   ↓
Uploading
   ↓
Progress Updates
   ↓
Success ─────→ Display File
   |
   └──────────→ Save Metadata

If Error
   ↓
Show Error
   ↓
Allow Retry

64. File Management Operations

Operation Firebase Storage Method
Upload local fileputFile()
Upload raw bytesputData()
Upload encoded stringputString()
Get URLgetDownloadURL()
Get bytesgetData()
Download locallywriteToFile()
Get metadatagetMetadata()
Update metadataupdateMetadata()
List fileslist() / listAll()
Delete filedelete()
Pause uploadpause()
Resume uploadresume()
Cancel uploadcancel()

65. Firebase Storage vs Firestore

Firebase Storage Cloud Firestore
Stores actual filesStores structured application data
Images and videosDocuments and fields
PDFs and audioStrings, numbers, arrays, objects
Uses Storage referencesUses collections and documents
Provides file URLsCan store those URLs

66. Example: Product Management

A product management application can use Firebase Storage for product images and Firestore for product information.

Storage:
products/product123/image.jpg
Firestore:
products/product123
{
  "name": "Laptop",
  "price": 65000,
  "imageUrl": "https://...",
  "storagePath": "products/product123/image.jpg"
}

67. Example: Profile Management

Storage:
users/user123/profile.jpg
Firestore:
users/user123
{
  "name": "Rahul",
  "email": "[email protected]",
  "profileImage": "https://..."
}

68. Best Practices for Image Management

  • Use meaningful Storage paths.
  • Use user IDs for user-specific content.
  • Generate unique file names when historical files must be preserved.
  • Use fixed paths when an object should simply be replaced.
  • Validate file type before upload.
  • Validate file size before upload.
  • Use correct MIME types.
  • Show upload progress.
  • Handle upload errors.
  • Store useful application metadata in Firestore rather than relying on custom Storage metadata for application data.
  • Delete unused files when appropriate.
  • Use restrictive Security Rules.

69. Best Practices for File Management

  1. Separate file management logic from UI code.
  2. Use a reusable Storage service.
  3. Use Firebase Authentication for private user files.
  4. Organize files into predictable paths.
  5. Do not make private files publicly writable.
  6. Monitor file upload progress.
  7. Handle network failures gracefully.
  8. Use appropriate download methods for large files.
  9. Keep Firestore metadata synchronized with Storage files.
  10. Clean up orphaned files.
  11. Monitor storage usage and project billing.

70. Common Mistakes

  • Forgetting to install firebase_storage.
  • Not configuring Firebase correctly.
  • Trying to upload directly to the Storage root.
  • Using incorrect Storage paths.
  • Not checking whether the user selected a file.
  • Not validating file size.
  • Not validating file type.
  • Not handling Storage exceptions.
  • Not showing upload progress.
  • Using unrestricted Security Rules in production.
  • Forgetting to save the download URL when the application needs it.
  • Deleting a Firestore record without deleting the corresponding Storage file.
  • Deleting a Storage file without updating the related Firestore record.

71. Mini Project: User Profile Image Manager

Create a Flutter application with the following functionality:

  1. User registers or logs in with Firebase Authentication.
  2. User opens the profile screen.
  3. User selects an image from the gallery.
  4. Application validates the image.
  5. Image is uploaded to Firebase Storage.
  6. Upload progress is displayed.
  7. Download URL is generated.
  8. Profile document is updated in Firestore.
  9. Image is displayed on the profile screen.
  10. User can replace the image.
  11. User can delete the image.

72. Mini Project: File Manager

Build a simple file management application with:

  • File selection
  • Image upload
  • PDF upload
  • File validation
  • Upload progress
  • File listing
  • File preview
  • Download option
  • Delete option
  • File metadata display
  • User-specific file access

73. Interview Questions

  1. What is Firebase Storage?
  2. How do you upload an image from Flutter to Firebase Storage?
  3. What is a Firebase Storage Reference?
  4. What is the purpose of putFile()?
  5. What is the difference between putFile(), putData(), and putString()?
  6. How do you obtain a download URL?
  7. How do you display a Firebase Storage image in Flutter?
  8. How do you monitor upload progress?
  9. How do you pause and resume an upload?
  10. How do you cancel an upload?
  11. How do you download a file from Firebase Storage?
  12. What is the difference between getData() and writeToFile()?
  13. What is Firebase Storage metadata?
  14. How do you update file metadata?
  15. How do you delete a file?
  16. How do you list files in Firebase Storage?
  17. How do Firebase Storage Security Rules work?
  18. How can Firebase Authentication be used with Storage?
  19. Why should file metadata sometimes be stored in Firestore?
  20. How would you design a user profile image upload system?

74. Quick Revision

Concept Key Point
Firebase StorageCloud storage for application files.
Packagefirebase_storage
Storage instanceFirebaseStorage.instance
ReferencePoints to a Storage location.
UploadputFile()
Download URLgetDownloadURL()
Download bytesgetData()
Local downloadwriteToFile()
MetadatagetMetadata()
Update metadataupdateMetadata()
List fileslist() / listAll()
Deletedelete()
ProgresssnapshotEvents
SecurityFirebase Storage Security Rules

75. Learning Outcomes

After completing this topic, you should be able to:

  • Explain how Firebase Storage works with Flutter.
  • Configure Firebase Storage in a Flutter project.
  • Select images and files from a device.
  • Upload images and documents.
  • Generate unique Storage paths.
  • Monitor upload progress.
  • Pause, resume, and cancel uploads.
  • Generate download URLs.
  • Display uploaded images.
  • Download files.
  • Read and update file metadata.
  • List files in a Storage location.
  • Delete and replace files.
  • Connect Storage with Firestore.
  • Apply Firebase Storage Security Rules.
  • Build reusable file-management services.

76. Useful Official Resources

77. JustAcademy Flutter Resources

78. Summary

Uploading and managing images and files is an important part of Flutter application development. Firebase Storage provides the cloud infrastructure required to store images, videos, PDFs, audio files, and other user-generated content.

In Flutter, the firebase_storage package provides APIs for creating Storage references, uploading files, monitoring upload progress, obtaining download URLs, downloading files, managing metadata, listing files, and deleting files.

A robust application should combine Firebase Storage with Firebase Authentication, Cloud Firestore, validation, error handling, and Security Rules. Storage should contain the actual files, while Firestore can contain related application data such as file URLs, Storage paths, user IDs, names, and timestamps.

whatsapp